import { h } from './element';
import { cssPrefix } from '../config';
import Button from './button';
import Icon from './icon';
import { t } from '../locale/locale';

const btnClick = function (type) {
  if (type === 'close') {
    this.isHide = true;
    this.el.hide();
  }
};
const setCellDatadb = function(code,dataDb){
  let params = {
    label: '='+ dataDb.label +'.' + code.label,
    value: dataDb.value+'.'+code.value
  }
  console.log(params)
  this.data.setSelectedCellAttr('bindFiled',params)
  this.change()
}
const addListDom = function(list){
  let echo = [];
  list.forEach((item,index)=>{
    let labelDom,dlDom,itemDom;
    echo.push(
      itemDom = h('div',`${cssPrefix}-dataDb-item`).children(
        labelDom = h('label',`${cssPrefix}-dataDb-item-label`).children(
          new Icon('chevron-down','down'),
          new Icon('chevron-right','right'),
          h('span').html(item.label)
        ),
        dlDom = h('dl',`${cssPrefix}-dataDb-item-cont`).children(
          ...addItemDom.call(this,item,index)
        )
      )
    );
    if(index === 0){
      itemDom.addClass('extand');
    }
    labelDom.on('click',()=>{
      if(itemDom.hasClass('extand')){
        itemDom.removeClass('extand')
      }else{
        itemDom.addClass('extand')
      }
    })
  })
  return echo.length == 0?['']:echo;
},
addItemDom = function(item){
  let echo = [];
  item.codes.forEach(code=>{
    echo.push(
      h('dd',`${cssPrefix}-dataDb-item-code`).data('dataDb',item)
      .html(code.label)
      .on('dblclick',setCellDatadb.bind(this,code,item))
    )
  })
  return echo.length == 0?['']:echo;
},
render = function(list){
  this.listEl.html('');
  this.listEl.children(...addListDom.call(this,list))
};
export default class DataDb{
  constructor(data){
    this.isHide = true;
    this.data = data;
    this.el = h('div', `${cssPrefix}-dataDb`)
      .children(
        h('div',`${cssPrefix}-dataDb-bar`).children(
          h('div', '-title').child(t('dataDb.title')),
          h('div', '-right').children(
            h('div', `${cssPrefix}-buttons`).children(
              new Button('close').on('click', btnClick.bind(this, 'close')),
              new Button('ok', 'primary').on('click', btnClick.bind(this, 'ok')).hide(),
            ),
          ),
        ),
        h('div',`${cssPrefix}-dataDb-content`).children(
          this.listEl = h('div',`${cssPrefix}-dataDb-list`)
        )
      ).hide()
  }
  reset(){
    if (this.isHide) return;
    const { data } = this;
    render.call(this,data.dataDb);
  }
  resetData(data) {
    this.data = data;
    this.reset();
  }
  open(){
    this.isHide = false;
    this.reset();
    this.el.show();
  }
}